package com.hermit.qmst.UI.activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;
import com.hermit.qmst.R;
import com.hermit.qmst.UI.XlistView.XListView;
import com.hermit.qmst.adapter.MessageAdapter;
import com.hermit.qmst.mode.MessageInfo;
import com.hermit.qmst.tools.Common;
import com.hermit.qmst.tools.Log;
import com.hermit.qmst.tools.Preferences;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * Created by Administrator on 2016/10/5 0005.
 */
public class MessageAcitivity extends Activity implements XListView.IXListViewListener, View.OnClickListener, AdapterView.OnItemClickListener {
    private String TAG = "MessageAcitivity";
    private TextView title;
    private XListView mListView;
    private MessageAdapter adapter;
    private int indexPage = 0;
    private Preferences preferences;
    private ProgressDialog mProgressDialog;
    private String uid, aid;
    private Handler mHandler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_message);
        preferences = new Preferences(MessageAcitivity.this);
        mHandler = new Handler();
        initView();
    }

    private void initView() {
        title = (TextView) findViewById(R.id.tv_title);
        title.setText("消息");
        ((ImageView) findViewById(R.id.iv_title_left)).setImageResource(R.drawable.ic_back);
        findViewById(R.id.iv_title_left).setOnClickListener(this);
        mListView = (XListView) findViewById(R.id.xListView);
        adapter = new MessageAdapter(MessageAcitivity.this);
        mListView.setAdapter(adapter);
        mListView.setOnItemClickListener(this);
        mListView.setXListViewListener(this);
        mListView.setPullLoadEnable(false);
        getData();
    }

    private void onLoad() {
        mListView.stopRefresh();
        mListView.stopLoadMore();
        mListView.setRefreshTime("刚刚");
    }


    @Override
    public void onRefresh() {
//        mHandler.postDelayed(new Runnable() {
//            @Override
//            public void run() {
        indexPage = 0;
        adapter.data.clear();
        adapter = new MessageAdapter(MessageAcitivity.this);
        mListView.setAdapter(adapter);
        getData();
//            }
//        }, 1000);
    }

    @Override
    public void onLoadMore() {
//        mHandler.postDelayed(new Runnable() {
//            @Override
//            public void run() {
        indexPage++;
        getData();
        adapter.notifyDataSetChanged();
//                onLoad();
//            }
//        }, 1000);
    }

    private void getData() {
        mProgressDialog = ProgressDialog.show(this, "提示", "系统正在处理，请稍后…", false, false);
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        aid = preferences.getPreferenceStringValue(Preferences.SIP_AGENT);
//        aid = "2";
        String url = Common.submitMessageList() + "&aid=" + aid +
                "&uid=" + Common.mUserId + "&page=" + indexPage;
        Log.i(TAG, "getData = " + url, true);
        JsonArrayRequest request = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
            @Override
            public void onResponse(JSONArray jsonArray) {
                try {
                    onLoad();
                    Log.i(TAG, "getData = " + jsonArray.toString(), true);
                    if (jsonArray.length() > 0) {
                        for (int i = 0; i < jsonArray.length(); i++) {
                            JSONObject object = jsonArray.getJSONObject(i);
                            MessageInfo info = new MessageInfo();
                            info.setId(object.getString("id"));
//                            info.setRead(object.getString("read"));
                            info.setCreatetime(object.getString("createtime"));
                            Log.i(TAG, object.getString("createtime"), true);
                            info.setTitle(object.getString("title"));
                            info.setContent(object.getString("content"));
                            Log.i(TAG, object.getString("content"), true);
                            info.setType(object.getInt("type"));
                            info.setReadtype(object.getInt("Readtype"));
                            adapter.data.add(info);
                        }
                        if (jsonArray.length() > Common.indexCount) {
//                            Toast.makeText(MessageAcitivity.this,"size:"+adapter.data.size(),Toast.LENGTH_LONG).show();
                            mListView.setPullLoadEnable(true);
                        }
                    } else {
                        adapter.data.clear();
                        Toast.makeText(MessageAcitivity.this, "暂无更多数据", Toast.LENGTH_SHORT).show();
                    }
                    adapter.notifyDataSetChanged();
                } catch (JSONException e) {
                    e.printStackTrace();
                } finally {
                    mProgressDialog.dismiss();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                mProgressDialog.dismiss();
//                onLoad();
            }
        });
        requestQueue.add(request);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Intent intent = new Intent(MessageAcitivity.this, MessageDetailsAcitivity.class);
        MessageInfo messageInfo = adapter.data.get(position - 1);
        Log.i(TAG, messageInfo.toString(), true);
        Bundle mBundle = new Bundle();
        mBundle.putSerializable("message_data", messageInfo);
        intent.putExtras(mBundle);
        intent.putExtra("message_data_id", position);
        startActivityForResult(intent, 0);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_title_left:
                finish();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        adapter.notifyDataSetChanged();
    }
}
